package com.lijianlove.keeplearning.multDatasource;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.lijianlove.keeplearning.dr.support.annotation.DR;
import com.lijianlove.keeplearning.dr.support.annotation.DRField;
import com.lijianlove.keeplearning.entity.User;
import com.lijianlove.keeplearning.strategy.UserStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author lijian
 * @date 2019/4/28 上午11:17
 */
@Slf4j
@DS("db_1")
@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserStrategy userStrategy;

    public List<Map<String, Object>> selectAll() {
        return jdbcTemplate.queryForList("select * from user");
    }

    @DS("db_2")
    public List<Map<String, Object>> selectByCondition() {
        return jdbcTemplate.queryForList("select * from user where age >10");
    }

    /**
     * 注意这里，没有事务，多数据源就会生效效
     *
     * @return
     */
    public void save() {
        Random random = userStrategy.saveToDb1(jdbcTemplate);

        userStrategy.saveToDb2(random, jdbcTemplate);
    }

    /**
     * 注意这里，一旦加上事务，多数据源就会失效
     * 因为对于事务，事务开始的时候就会获取connection , 事务中一直使用的这个connection @see DataSourceTransactionManager
     */
    @Transactional
    public void testTransactional(User user) {
        Random random = userStrategy.saveToDb1(jdbcTemplate);
//        int i = 1 / 0;
        userStrategy.saveToDb2(random, jdbcTemplate);
    }


}
